package com.pinkmeet.websocket;

/**
 * Created by mars on 2018/5/9.
 */
import java.net.InetSocketAddress;
import java.sql.Date;
import java.util.Calendar;

import com.pinkmeet.dao.ConnDAO;
import com.pinkmeet.dao.MessagesDAO;
import com.pinkmeet.dao.UserDAO;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.json.JSONException;
import org.json.JSONObject;

public class WsSever extends WebSocketServer {
    public WsSever(int port) {
        super(new InetSocketAddress(port));
    }

    public WsSever(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        // ws连接的时候触发的代码，onOpen中我们不做任何操作 等待浏览器发送用户id

    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        //断开连接时候触发代码 更改用户在线状态
        String id = WsPool.getUserByWs(conn);
        UserDAO.serOffLine(Integer.parseInt(id));

        userLeave(conn);
        System.out.println(reason);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        //将message解析成json代码
        ConnDAO con = new ConnDAO();

        try {
            JSONObject json = new JSONObject(message);
            String type =  ""+json.get("type");
            String cid;
            int ccid;
            WebSocket pconn;
            switch (type){
                //上线消息
                case "0":
                     cid = ""+json.get("id");
                    userJoin(conn,cid);
                    ccid = con.getChatById(Integer.parseInt(cid));
                    //加入连接池
                    pconn = WsPool.getWsByUser(""+ccid);
                    //更改用户在线状态
                    UserDAO.setOnLine(Integer.parseInt(cid));

                    if (pconn!=null){
                        JSONObject online = new JSONObject();
                        online.put("type",0);
                        online.put("id",cid);
                        pconn.send(online.toString());
                    }

                    break;

                //普通聊天消息
                case "1":
                    cid = WsPool.getUserByWs(conn);
                    ccid = con.getChatById(Integer.parseInt(cid));
                    pconn = WsPool.getWsByUser(""+ccid);
                    //把消息转发
                    if (pconn!=null){
                        pconn.send(message);
                    }

                    MessagesDAO msdao = new MessagesDAO();
                    java.util.Date time = new java.util.Date();
                    //存入数据库
                    msdao.saveMessage(Integer.parseInt(cid),ccid,json.getString("content"),new java.util.Date());

                    break;

                //离线消息
                case "2":
                    cid = WsPool.getUserByWs(conn);
                    ccid = con.getChatById(Integer.parseInt(cid));
                    pconn = WsPool.getWsByUser(""+ccid);
                    if (pconn!=null){
                        JSONObject online = new JSONObject();
                        online.put("type",2);
                        online.put("id",cid);
                        pconn.send(online.toString());
                    }

                    break;
            }


        } catch (JSONException e) {
            e.printStackTrace();

        }


        System.out.println(message);
        if (null != message && message.startsWith("online")) {
            String userName = message.replaceFirst("online", message);//用户名
            userJoin(conn, userName);//用户加入
        } else if (null != message && message.startsWith("offline")) {
            userLeave(conn);
        }

    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        //错误时候触发的代码
        System.out.println("on error");
        ex.printStackTrace();
    }

    /**
     * 去除掉失效的websocket链接
     *
     * @param conn
     */
    private void userLeave(WebSocket conn) {
        WsPool.removeUser(conn);
    }

    /**
     * 将websocket加入用户池
     *
     * @param conn
     * @param userName
     */
    private void userJoin(WebSocket conn, String userName) {
        WsPool.addUser(userName, conn);
    }
}